<template>
  <div class="conetr">
    <div class="center-board">
      <div class="center-title">
        <h3>设计关联</h3>
      </div>
      <div class="action-bar mb-[20px]">
        <el-button icon="Back" type="primary" plain text @click="backTo">返回</el-button>
        <el-button
          icon="Download"
          type="success"
          plain
          @click="handleSubmit"
          :disabled="!canEdit"
          :loading="loading"
        >
          保存
        </el-button>
      </div>
    </div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      class="form"
      :disabled="!canEdit"
    >
      <el-form-item label="姓名" prop="designerName">
        <el-input
          v-model.number.trim="formData.designerName"
          disabled
          placeholder="请输入设计师姓名"
        />
      </el-form-item>
      <el-form-item label="电话" prop="designerPhone">
        <el-input
          v-model.number.trim="formData.designerPhone"
          disabled
          placeholder="请输入设计师电话"
        />
      </el-form-item>
      <el-form-item label="装修公司" prop="companyId">
        <el-select
          v-model="formData.companyId"
          filterable
          clearable
          placeholder="请选择装修公司"
          @change="handleChangeCompanyId"
        >
          <el-option
            v-for="item in decorationCompanyOptions"
            :key="item.id"
            :label="item.companyName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="decorationAddress">
        <el-input v-model="formData.decorationAddress" placeholder="请输入地址" disabled />
      </el-form-item>
      <el-form-item label="合同金额" prop="contractAmount">
        <el-input
          v-model.number.trim="formData.contractAmount"
          type="number"
          placeholder="请输入合同金额"
        />
      </el-form-item>
      <el-form-item label="合同时间" prop="contractTime">
        <el-date-picker
          v-model="formData.contractTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择合同时间"
        />
      </el-form-item>
      <el-form-item label="设计合同" prop="contractFile">
        <FilesUpload
          v-model="formData.contractFile"
          :disabled="!canEdit"
          v-model:loading="contractFileLoading"
          :limit="20"
          accept=".jpeg,.png,.jpg,.bmp,.pdf"
        ></FilesUpload>
        <!-- <MultiImageUpload
          v-model="formData.contractFile"
          :disabled="!canEdit"
          v-model:loading="contractFileLoading"
          :limit="20"
          accept=".jpeg,.png,.jpg,.bmp,.pdf"
        /> -->
      </el-form-item>
      <el-form-item label="收款凭证" prop="receiptFile">
        <MultiImageUpload
          v-model="formData.receiptFile"
          :disabled="!canEdit"
          :limit="2"
          v-model:loading="receiptFileLoading"
        />
      </el-form-item>
      <el-form-item v-if="formData.remark" label="驳回理由">
        <el-input v-model="formData.remark" disabled placeholder="" />
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import FilesUpload from "@/components/Upload/FilesUpload.vue";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";

import { ElMessage } from "element-plus";
import HouseAPI, { ConsumerHouseDesignLinkForm } from "@/api/house";
import opportunityPaymentAPI from "@/api/opportunityPayment";
// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData", "backTo"]);

const dialog = reactive({
  title: "",
  visible: false,
});
const formRef = ref();
const decorationCompanyOptions = ref([]);
const paymentFileLoading = ref(false);
const contractFileLoading = ref(false);
const receiptFileLoading = ref(false);
const defaultFormData: ConsumerHouseDesignLinkForm = {
  id: undefined,
  contractAmount: undefined,
  designerName: "",
  designerPhone: "",
  houseId: undefined,
  contractTime: "",
  businessAddress: "",
  companyId: undefined,
  decorationCompanyName: "",
  decorationAddress: "",
  merchantUserId: undefined,
  paymentFile: [],
  receiptFile: [],
  contractFile: [],
};
const formData = ref<ConsumerHouseDesignLinkForm>({
  ...defaultFormData,
});
const loading = computed(
  () => paymentFileLoading.value || contractFileLoading.value || receiptFileLoading.value
);

function backTo() {
  emit("backTo");
}
const formRules = reactive({
  // companyId: [{ required: true, message: "请选择装修公司", trigger: "change" }],
  contractTime: [{ required: true, message: "请选择合同时间", trigger: "change" }],
  contractAmount: [
    { type: "number", message: "合同金额必须为数字" },
    { type: "number", max: 999999999, message: "合同金额超出最大值" },
    { required: true, message: "请输入合同金额", trigger: "blur" },
  ],
  // decorationAddress: [{ required: true, message: "请输入地址", trigger: "blur" }],
  paymentFile: [{ required: true, message: "请上传付款凭证", trigger: "change" }],
  contractFile: [{ required: true, message: "请上传设计合同", trigger: "change" }],
  receiptFile: [{ required: true, message: "请上传收款凭证", trigger: "change" }],
});
async function handleSubmit() {
  const validate = await formRef.value.validate();
  if (!validate) return;
  try {
    await HouseAPI.houseDesignLinkEdit({
      ...formData.value,
      paymentFile: JSON.stringify(formData.value.paymentFile),
      receiptFile: JSON.stringify(formData.value.receiptFile),
      contractFile: JSON.stringify(formData.value.contractFile),
    });
    ElMessage.success("成功");
    emit("loadData");
    emit("backTo");
    handleCloseDialog();
  } catch (error) {
    console.log("error", error);
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  Object.assign(formData.value, defaultFormData);
  emit("update:modelValue", false); // 关闭弹窗
}
const canEdit = ref(true);
function showModal(val, cannotEdit = false) {
  canEdit.value = !cannotEdit;
  dialog.visible = true;
  const { nickname, mobile, userId } = val.merchantUser;
  const {
    paymentFile,
    receiptFile,
    contractFile,
    companyId,
    decorationCompanyName,
    decorationAddress,
  } = val.house.houseDesignLinkVO || {};
  Object.assign(formData.value, defaultFormData, val.house.houseDesignLinkVO, {
    designerName: nickname,
    designerPhone: mobile,
    houseId: val.houseId,
    merchantUserId: userId,
    paymentFile: JSON.parse(paymentFile || "[]"),
    receiptFile: JSON.parse(receiptFile || "[]"),
    contractFile: JSON.parse(contractFile || "[]"),
    companyId: companyId,
    decorationCompanyName: decorationCompanyName,
    decorationAddress: decorationAddress,
  });
  getCompanyList();
}

async function getCompanyList() {
  try {
    const data = await opportunityPaymentAPI.getCompanyList({
      houseId: formData.value.houseId,
      chatUserId: formData.value.merchantUserId,
    });
    decorationCompanyOptions.value = data;
  } catch (e) {
    console.log(e);
  }
}

function handleChangeCompanyId(val) {
  const { companyName, businessAddress } =
    decorationCompanyOptions.value.find((item) => item.id === val) || {};
  formData.value.decorationCompanyName = companyName;
  formData.value.decorationAddress = businessAddress;
}

defineExpose({
  showModal,
});
</script>
<style scoped lang="scss">
::v-deep(.el-tabs__content) {
  min-height: 100px;
  display: flex;
  align-items: center;
}
.conetr {
  background-color: #fff;
  position: relative;
  flex: 1;
  box-sizing: border-box;
  padding: 10px 20px;

  .center-board {
    .center-title {
      position: absolute;
      left: 20px;
    }
    .action-bar {
      position: relative;
      box-sizing: border-box;
      padding: 10px 0 15px 0;
      border-bottom: 1px solid var(--el-border-color-extra-light);
      display: flex;
      align-items: center;
      justify-content: flex-end;

      u .delete-btn {
        color: #f56c6c;
      }
    }
  }
}
</style>
